package com.doudanhua.basecode.jackson.time;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Date;

/**
 * @Author zhangqian
 * @Description TODO
 * @Date 2022/11/4 17:14
 */
public class NormalDateTimeConverter extends DateTimeConverter {
    @Override
    protected ZonedDateTime parse(String value) {
        TemporalAccessor temporalAccessor = dateTimeFormatter.parseBest(value, ZonedDateTime::from, LocalDateTime::from, LocalDate::from);
        if (temporalAccessor instanceof ZonedDateTime)
            return ((ZonedDateTime) temporalAccessor).withZoneSameInstant(ZoneId.systemDefault());
        if (temporalAccessor instanceof LocalDateTime)
            return ((LocalDateTime) temporalAccessor).atZone(ZoneId.systemDefault());
        return ((LocalDate) temporalAccessor).atStartOfDay(ZoneId.systemDefault());
    }

    public String format(Date value) {
        return ZonedDateTime.ofInstant(value.toInstant(), ZoneId.systemDefault()).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    }

    public String format(LocalDateTime value) {
        return value.atZone(ZoneId.systemDefault()).format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    }

    public String format(ZonedDateTime value) {
        return value.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
    }
}
